package cn.com.connext.scrm.service.mapper;

import cn.com.connext.scrm.domain.master.Comment;
import cn.com.connext.scrm.repository.master.CommentLikesRepository;
import cn.com.connext.scrm.repository.master.CommentRepository;
import cn.com.connext.scrm.service.dto.CommentDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.ArrayList;
import java.util.List;

public abstract class CommentMapperDecorator implements CommentMapper {

    @Autowired
    @Qualifier("delegate")
    private CommentMapper delegate;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private CommentLikesRepository commentLikesRepository;

    @Override
    public CommentDTO toDto(Comment comment) {
        CommentDTO commentDTO = delegate.toDto(comment);
        //评论的点赞数
        int count_likes = 0;
        //评论的回复数
        int count_reply = 0;

        if (StringUtils.isNotEmpty(comment.getContent())) {
            count_likes = commentLikesRepository.countAllCommentLikes(comment.getContent());
        }
        //评论的回复数以及回复列表（只有一级评论才有回复列表）
        if (StringUtils.isNotEmpty(comment.getId())
            && StringUtils.isNotEmpty(comment.getReplyType().toString())
            && 0 == comment.getReplyType()) {
            String Id = comment.getId();
            count_reply = commentRepository.countTotalReplay(Id);

            //该条评论的回复列表
            List<CommentDTO> replyList = new ArrayList<>();
            List<Comment> commentList = commentRepository.findAllReply(Id);
            for (Comment item : commentList) {
                CommentDTO newCommentDTO = delegate.toDto(item);
                replyList.add(newCommentDTO);
            }
            commentDTO.setReplyList(replyList);
            commentDTO.setReplaySize(replyList == null ? 0 : replyList.size());
            commentDTO.setCommentId(comment.getId());

        }
        commentDTO.setTotalCommentLikes(count_likes);
        commentDTO.setTotalReply(count_reply);
        return commentDTO;
    }
}
